package com.ruoyi.tcp.client;

import com.ruoyi.tcp.messager.CustomerMessageDecoder;
import com.ruoyi.tcp.messager.CustomerMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author 蒋翔 SY100242
 * @date 2024/8/5 11:30
 * @email SY100242@hnlens.com
 */
public class TcpClient {
    private static Logger log = LoggerFactory.getLogger(TcpClient.class);

    public static void main(String[] args) {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(0,3,0));
                            pipeline.addLast(new CustomerMessageDecoder());
                            pipeline.addLast(new CustomerMessageEncoder());
                            pipeline.addLast(new TestClientCustomerHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.connect(TestClientCustomerHandler.clientChannel.getHost(), TestClientCustomerHandler.clientChannel.getPort()).sync();
//            ChannelFuture sync = bootstrap.connect("218.17.241.75", 6689).sync();
//            ChannelFuture sync = bootstrap.connect("182.254.194.127", 8883).sync();
//            ChannelFuture sync = bootstrap.connect("127.0.0.1", 8883).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }


}
